const fs = require('fs')

/**
 * 读取文件
 */
const readFile = (path) => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, (err, data) => {
      if (err) {
        reject(new Error(`${path}文件读取失败 ${err}`))
      } else {
        resolve(data)
      }
    })
  })
}

/**
 * 写入文件
 */
const writeFile = (path, data, options = { encoding: 'utf8' }) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, options,
      err => { err ? reject(new Error(`${err} ${path}文件写入失败`)) : resolve() })
  })
}

/**
 * 查询文件是否存在
 */
const isExists = (path) => {
  return new Promise(resolve => {
    fs.access(path, fs.constants.F_OK, (err) => {
      err ? resolve(false) : resolve(true)
    })
  })
}

/**
 * 删除文件
 */
const delFile = (path) => {
  return new Promise((resolve, reject) => {
    fs.unlink(path, (err) => {
      err ? reject(new Error(`${err} ${path}文件删除失败`)) : resolve()
    });
  })
}
module.exports = { readFile, writeFile, isExists, delFile }